package com.module.overview.ui.cardHistoryDetails.provider

import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.CalendarDay
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.utils.AppUtils.getString
import com.common.base.utils.JsonUtils
import com.common.base.utils.ViewUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.data.bean.CusChartData
import com.module.ble.repo.BloodOxygenRepo
import com.module.ble.repo.HeartRateRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.widget.CandlestickChart
import com.module.overview.R
import java.util.Calendar

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/11
 *
 * 描述：体征-血氧饱和度卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvSignsOxyCardProvider(mCalendar: CalendarDay?,
                             override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_SIGNS_OXY,
                             override val layoutId: Int = R.layout.overview_signs_oxy_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    var mCalendar = mCalendar
    private var curTime = mCalendar?.toCalendar()?.timeInMillis?:0

    var tvMeasure: TextView? = null
    var tvAverageOxy: TextView? = null
    var tvLastTime: TextView? = null
    var tvTheDayAverage: TextView? = null
    var tvTheDayScope: TextView? = null
    private var candlestickChart: CandlestickChart? = null

    private val earlyMorningStr = ViewUtils.getString(R.string.common_rail_unit)
    private val morningStr  = ViewUtils.getString(R.string.common_rail_unit)
    private val afternoonStr  = ViewUtils.getString(R.string.common_rail_unit)
    private val eveningStr  = ViewUtils.getString(R.string.common_rail_unit)

    // 设置数据（48个30分钟间隔的数据）
    private val stressData = mutableListOf<CusChartData>()

    var measureResult :Number = -1

    init {
        val currentTime = System.currentTimeMillis()
        val startOfDay = currentTime - (currentTime % (24 * 60 * 60 * 1000)) // 当天0点时间戳

        for (index in 0 until 48) {
            val timeOffset = index * 30 * 60 * 1000L // 每30分钟的时间偏移
            val timestamp = startOfDay + timeOffset

            // 根据实际压力数据设置值（0-100）
            val minValue = when {
                index < 12 -> (90 + (1..3).random()).toFloat() // 0-6点
                index < 24 -> (90 + (1..2).random()).toFloat() // 6-12点
                else -> (90 + (1..3).random()).toFloat() // 12-24点
            }

            stressData.add(
                CusChartData(
                    createdTime = timestamp,
                    minValue = minValue,
                    mValue = minValue+(1..5).random(),
                    dayNum = 0
                )
            )
        }
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {
        // 设置Y轴阶段
        candlestickChart?.setYAxisStages(
            floatArrayOf(90f, 95f, 100f), // 阶段分界点
        )
//        // 在代码中设置数据
//        candlestickChart?.setData(stressData)

        getTheDayOxy()
    }


    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
//        tvEarlyMorningCk = viewHolder.getView(R.id.tvEarlyMorningCk)
        tvAverageOxy = viewHolder.getView(R.id.tvAverageOxy)
        tvMeasure = viewHolder.getView(R.id.tvMeasure)
        tvLastTime = viewHolder.getView(R.id.tvLastTime)
        tvTheDayAverage = viewHolder.getView(R.id.tvTheDayAverage)
        tvTheDayScope = viewHolder.getView(R.id.tvTheDayScope)
        candlestickChart = viewHolder.getView(R.id.candlestickChart)
        viewHolder.setVisible(R.id.tvMeasure, (mCalendar?.dateName == getString(R.string.common_today_hint)))
        LiveEventBus.get(KeyEvents.KEY_OV_SET_OXY_MEASUREMENT_LISTENER).post(this)

        // 设置触摸监听
        candlestickChart?.setOnBarTouchListener(object : CandlestickChart.OnBarTouchListener {

            override fun onBarTouched(
                index: Int,
                minValue: Float,
                maxValue: Float,
                timeLabel: String,
                extStr: String
            ) {
                // 处理触摸事件
//                Log.d("CandlestickChart", "触摸到柱子: 索引=$barIndex,触摸到: $timeLabel, 值: $minValue")
                tvAverageOxy?.text = "${if (minValue.toInt() <= 0) ViewUtils.getString(R.string.common_rail_unit) else minValue.toInt()}~${if (maxValue.toInt() <= 0) ViewUtils.getString(R.string.common_rail_unit) else maxValue.toInt()}"
                tvLastTime?.text = extStr
            }

            override fun onAverageLineTouched(
                index: Int,
                minValue: Float,
                maxValue: Float,
                timeLabel: String,
                extStr: String
            ) {
            }

            override fun onTouchReleased() {
                // 处理触摸释放事件
                tvAverageOxy?.text = if (measureResult.toInt() <= -1) ViewUtils.getString(R.string.common_rail_unit) else measureResult.toString()
                tvLastTime?.text = ViewUtils.getString(R.string.common_last_time_hint)
            }
        })
        super.onViewHolderCreated(viewHolder, viewType)
    }

    /**
     * 获取当天血氧
     */
    fun getTheDayOxy(){
        if (curTime <=0) return

        doOnIOThread {
            //当天血氧
            BloodOxygenRepo.instance.findByOneDay(curTime)?.let { originalListIt->
                if (originalListIt.isNullOrEmpty()) return@let

                val listItStr = JsonUtils.toJson(originalListIt)

                // 创建48个时间区间块的CusChartData数组
                val stressListData = mutableListOf<CusChartData>()

                // 获取curTime当天的0点时间戳
                val calendar = Calendar.getInstance()
                calendar.timeInMillis = curTime
                calendar.set(Calendar.HOUR_OF_DAY, 0)
                calendar.set(Calendar.MINUTE, 0)
                calendar.set(Calendar.SECOND, 0)
                calendar.set(Calendar.MILLISECOND, 0)
                val startOfDay = calendar.timeInMillis

                for (index in 0 until 48) {
                    val timeOffset = index * 30 * 60 * 1000L // 每30分钟的时间偏移
                    val intervalStartTime = startOfDay + timeOffset
                    val intervalEndTime = startOfDay + timeOffset + (30 * 60 * 1000L) // 加30分钟作为结束时间

                    // 查找在当前时间区间内的心率数据
                    val dataInInterval = originalListIt.filter { oxyRateData ->
                        oxyRateData.createdTime in intervalStartTime until intervalEndTime
                    }

                    var extStr = ""

                    // 生成extStr，格式为"最小值~最大值"
                    var minValue = 0
                    var maxValue = 0

                    if (dataInInterval.isNotEmpty()) {
                        // 生成extStr，格式为"最小值~最大值"
                        minValue = dataInInterval.minOfOrNull { it.bloodOxygen }?:0
                        maxValue = dataInInterval.maxOfOrNull { it.bloodOxygen }?:0
                        extStr = "$minValue~$maxValue"
                    }
                    else {
//                        // 如果区间内没有数据，设置为0
//                        mValue = -1f
                        extStr = ""
                    }

                    stressListData.add(
                        CusChartData(
                            createdTime = intervalStartTime,
                            endTime = intervalEndTime,
                            mValue = maxValue.toFloat(),
                            minValue = minValue.toFloat(),
                            exStr = extStr,
                            dayNum = 0
                        )
                    )
                }

                val stressListDataStr = JsonUtils.toJson(stressListData)
                val minTemp = ((originalListIt.minOfOrNull { it.bloodOxygen } ?: 0f).toFloat())
                val maxTemp = ((originalListIt.maxOfOrNull { it.bloodOxygen } ?: 0f).toFloat())
                val theDayAverage = if (originalListIt.isNotEmpty()) {//当日平均
                    originalListIt.map { it.bloodOxygen }.average().toInt().toString()
                } else {
                    ViewUtils.getString(R.string.common_rail_unit)
                }

                val latestBloodOxygen = originalListIt.maxByOrNull { it.createdTime }

                doOnUiThread {

                    latestBloodOxygen?.let {latestBloodOxygenIt->
                        measureResult = latestBloodOxygenIt.bloodOxygen
                        tvAverageOxy?.text = measureResult.toString()
                    }


                    tvTheDayAverage?.text = theDayAverage
                    tvTheDayScope?.text = "${minTemp.toInt()}~${maxTemp.toInt()}"

//                    // 设置Y轴阶段
//                    candlestickChart?.setYAxisStages(
//                        floatArrayOf(if(minTemp-10f <=0) 0f else minTemp-10f, ((maxTemp-minTemp)/2).toInt()+minTemp, maxTemp+10f), // 阶段分界点
//                    )
                    // 通知图表更新数据
                    candlestickChart?.setData(stressListData)
                }
            }
        }
    }
}